import django_filters
from django.db.models import Q
from django.utils import timezone
from datetime import datetime, timedelta
from .models import SurveyRecord, FavoriteLocation
import math

class SurveyRecordFilter(django_filters.FilterSet):
    # 基础文本搜索
    search = django_filters.CharFilter(method='filter_search', label='搜索')
    
    # 日期范围搜索
    start_date = django_filters.DateTimeFilter(field_name='survey_date', lookup_expr='gte', label='开始日期')
    end_date = django_filters.DateTimeFilter(field_name='survey_date', lookup_expr='lte', label='结束日期')
    
    # 地点名称搜索
    location_name = django_filters.CharFilter(field_name='location_name', lookup_expr='icontains', label='地点名称')
    
    # 地址搜索
    address = django_filters.CharFilter(field_name='address', lookup_expr='icontains', label='地址')
    
    # 备注搜索
    notes = django_filters.CharFilter(field_name='notes', lookup_expr='icontains', label='备注')
    
    # 朝向搜索
    orientation = django_filters.CharFilter(field_name='orientation', lookup_expr='icontains', label='朝向')
    
    # 地理位置范围搜索
    latitude_min = django_filters.NumberFilter(method='filter_latitude_range', label='最小纬度')
    latitude_max = django_filters.NumberFilter(method='filter_latitude_range', label='最大纬度')
    longitude_min = django_filters.NumberFilter(method='filter_longitude_range', label='最小经度')
    longitude_max = django_filters.NumberFilter(method='filter_longitude_range', label='最大经度')
    
    # 中心点+半径搜索
    center_lat = django_filters.NumberFilter(method='filter_radius', label='中心纬度')
    center_lng = django_filters.NumberFilter(method='filter_radius', label='中心经度')
    radius = django_filters.NumberFilter(method='filter_radius', label='搜索半径(km)')
    
    # 时间范围快捷选项
    time_range = django_filters.ChoiceFilter(
        method='filter_time_range',
        choices=[
            ('today', '今天'),
            ('week', '本周'),
            ('month', '本月'),
            ('quarter', '本季度'),
            ('year', '今年'),
        ],
        label='时间范围'
    )

    class Meta:
        model = SurveyRecord
        fields = []

    def filter_search(self, queryset, name, value):
        """基础搜索：支持地点名称、地址、备注的模糊搜索"""
        if not value:
            return queryset
        
        return queryset.filter(
            Q(location_name__icontains=value) |
            Q(address__icontains=value) |
            Q(notes__icontains=value) |
            Q(orientation__icontains=value)
        )
    
    def filter_latitude_range(self, queryset, name, value):
        """纬度范围过滤"""
        if not value:
            return queryset
        
        # 获取纬度最小值和最大值
        latitude_min = self.data.get('latitude_min')
        latitude_max = self.data.get('latitude_max')
        
        filters = {}
        if latitude_min:
            filters['latitude__gte'] = latitude_min
        if latitude_max:
            filters['latitude__lte'] = latitude_max
            
        return queryset.filter(**filters)
    
    def filter_longitude_range(self, queryset, name, value):
        """经度范围过滤"""
        if not value:
            return queryset
        
        # 获取经度最小值和最大值
        longitude_min = self.data.get('longitude_min')
        longitude_max = self.data.get('longitude_max')
        
        filters = {}
        if longitude_min:
            filters['longitude__gte'] = longitude_min
        if longitude_max:
            filters['longitude__lte'] = longitude_max
            
        return queryset.filter(**filters)
    
    def filter_radius(self, queryset, name, value):
        """中心点半径搜索"""
        center_lat = self.data.get('center_lat')
        center_lng = self.data.get('center_lng')
        radius = self.data.get('radius')
        
        if not all([center_lat, center_lng, radius]):
            return queryset
        
        # 使用简单的矩形边界框近似圆形搜索
        # 1度纬度约等于111km
        lat_delta = float(radius) / 111.0
        lng_delta = float(radius) / (111.0 * math.cos(math.radians(float(center_lat))))
        
        return queryset.filter(
            latitude__gte=float(center_lat) - lat_delta,
            latitude__lte=float(center_lat) + lat_delta,
            longitude__gte=float(center_lng) - lng_delta,
            longitude__lte=float(center_lng) + lng_delta
        )
    
    def filter_time_range(self, queryset, name, value):
        """时间范围快捷搜索"""
        now = timezone.now()
        
        if value == 'today':
            start = now.replace(hour=0, minute=0, second=0, microsecond=0)
            end = start + timedelta(days=1)
        elif value == 'week':
            # 本周一到现在
            days_since_monday = now.weekday()
            start = (now - timedelta(days=days_since_monday)).replace(hour=0, minute=0, second=0, microsecond=0)
            end = now
        elif value == 'month':
            # 本月1号到现在
            start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
            end = now
        elif value == 'quarter':
            # 本季度第一天到现在
            quarter_start_month = ((now.month - 1) // 3) * 3 + 1
            start = now.replace(month=quarter_start_month, day=1, hour=0, minute=0, second=0, microsecond=0)
            end = now
        elif value == 'year':
            # 今年1月1号到现在
            start = now.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
            end = now
        else:
            return queryset
            
        return queryset.filter(survey_date__gte=start, survey_date__lte=end)


class FavoriteLocationFilter(django_filters.FilterSet):
    # 地点名称搜索
    search = django_filters.CharFilter(method='filter_search', label='搜索')
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains', label='地点名称')
    address = django_filters.CharFilter(field_name='address', lookup_expr='icontains', label='地址')

    class Meta:
        model = FavoriteLocation
        fields = []

    def filter_search(self, queryset, name, value):
        """搜索地点名称和地址"""
        if not value:
            return queryset
        
        return queryset.filter(
            Q(name__icontains=value) |
            Q(address__icontains=value)
        )